<?php

if (COUNT($_POST) > 0)
{
	Connection::getConnect();
	if ($this->get('unitadd'))
	{
		$name = $this->get('name');
		$qty = $this->get('qty');
		$sql = "SELECT imdid FROM item_unit_detail WHERE name='%s'";
        Connection::setQueryf($sql, $name);
        $fetch = Connection::fetch();
        if (!$fetch[0])
    	{
    		$sql = "INSERT INTO item_unit_detail(name, default_per) VALUES('%s', %d)";
    		Connection::setQueryf($sql, $name, $qty);
    		$this->logger(INVENTORY, 'Item Unit Added - name="' . mysql_real_escape_string($name) . '" default="' . $qty . '".');
    		echo mysql_insert_id();
			exit;
		}
		echo 0;
		exit;
	}
	if ($this->get('remunit'))
	{
		$name = $this->get('name');
		$sql = "DELETE FROM item_unit_detail WHERE name='%s'";
		Connection::setQueryf($sql, $name);
		exit;
	}
	$name = $this->get('name');
	$desc = htmlspecialchars($this->get('desc'), ENT_QUOTES);
	$tag = $this->get('tag');
	
	$category = $this->get('category');
	$whole_sale = $this->get('whole_sale');
	$retail = $this->get('retail');
	$suppliers = $this->get('suppliers'); 
	$barcode = $this->get('barcode'); 
	$reorder = $this->get('reorder'); 
	$reorderq = $this->get('reorderq'); 
	
	if( strlen($name) < 0 || strlen($desc) < 4)
		exit;
	$sql = "SELECT iid FROM item_details WHERE name='%s'";
    Connection::setQueryf($sql, $name);
    $fetch = Connection::fetch();
    if ($fetch[0] > 0)
	{
		echo "Item Name Already Exist!";
		exit;
	}
	$sql = "INSERT INTO item_details(name, description, tags, date_enter) VALUES('%s', '%s', '%s', NOW())";
    Connection::setQueryf($sql, $name, $desc, $tag);
	$id = mysql_insert_id();
	if (isset($id))
	{
    	$sql = "INSERT INTO item_inventory(iid, whole_sale_price, retail_price, icid, barcode, reorder, reorder2) VALUES(%d, %d, %d, %d, '%s', %d, %d)";
        Connection::setQueryf($sql, $id, $whole_sale, $retail, $category, $barcode, $reorder, $reorderq);
    	foreach($suppliers as $supen){
			if(!isset($supen[0]) || COUNT($supen) < 4)
				continue;
    		$sql = "INSERT INTO supplier_item_cost(iid, sdid, cost, per_unit, imdid) VALUES($id, $supen[0], $supen[3], $supen[2], $supen[1])";
       		Connection::setQueryf($sql);
    	}
		$this->logger(INVENTORY, 'Item Added - name="' . $name . '".');
	}
	echo "id".$id;
	exit;
	//;
}
?>